package www.bplead.com;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import www.bplead.com.data.DeviceData;

/**
 * Created by wangyangzi on 2017/3/2.
 */

public class PairedActivity extends AppCompatActivity {

    private PopupWindow popupWindow;
    private View popupView;
    private View rootLayout;
    private ListView foundDeviceListView;
    private ListView pairedDeivceListView;

    private Set<BluetoothDevice> pairedDeviceSet;
    private ArrayAdapter<String> pairedDiviceAdapter;
    private ArrayList<String> pairedDeviceList;

    private BluetoothAdapter bluetoothAdapter;
    private ArrayAdapter<String> foundDiviceAdapter;
    private ArrayList<String> foundDeviceList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.device_pair);

        setTitle("设备查找");

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        pairedDeivceListView = (ListView) this.findViewById(R.id.paired_device);
        pairedDeivceListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //将选中设备设置为打印机
                String device = pairedDeviceList.get(position);
                DeviceData.getInstance(PairedActivity.this).setPrinterDevice(device);
                finish();
            }
        });
        foundDeviceListView = (ListView) this.findViewById(R.id.found_device);
        foundDiviceAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,foundDeviceList);
        foundDeviceListView.setAdapter(foundDiviceAdapter);
        foundDeviceListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获得选中设备mac地址
                String device = foundDeviceList.get(position);
                String mac = device.substring(device.indexOf("\n") + 1);
                // 发起配对请求
                try{
                    BluetoothDevice bd = bluetoothAdapter.getRemoteDevice(mac);
                    if (bd.getBondState() == BluetoothDevice.BOND_NONE){
                        Method creMethod = BluetoothDevice.class.getMethod("createBond");
                        creMethod.invoke(bd);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        rootLayout = getWindow().getDecorView();
        popupView = getLayoutInflater().inflate(R.layout.pop_up_device_finding,null);
        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,false);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_OUTSIDE){
                    popupWindow.dismiss();
                    bluetoothAdapter.cancelDiscovery();
                    return true;
                }
                return false;
            }
        });

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        //初始化已配对设备列表
        initPairedDevice();

        registerBroadcast();
    }

    private void initPairedDevice() {
        pairedDeviceSet = bluetoothAdapter.getBondedDevices();
        pairedDeviceList = new ArrayList<>();
        if(pairedDeviceSet.size() > 0){
            for(Iterator<BluetoothDevice> devices = pairedDeviceSet.iterator();devices.hasNext();){
                BluetoothDevice bd = devices.next();
                pairedDeviceList.add(bd.getName() + "\n" + bd.getAddress());
            }
        }
        pairedDiviceAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,pairedDeviceList);
        pairedDeivceListView.setAdapter(pairedDiviceAdapter);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.device_find:
                //检查是否开启蓝牙，如果未开启则提示开启
                if(!bluetoothAdapter.isEnabled()){
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivity(intent);
                }
                //开始搜素附近蓝牙设备
                else {
                    popupWindow.showAtLocation(rootLayout ,Gravity.CENTER,0,0);
                    bluetoothAdapter.startDiscovery();
                    break;
                }
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.device_scan,menu);
        return super.onCreateOptionsMenu(menu);
    }

    private void registerBroadcast(){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        intentFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        this.registerReceiver(receiver,intentFilter);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            //发现新设备
            String action = intent.getAction();
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
                switch (state) {
                    case BluetoothAdapter.STATE_TURNING_ON://蓝牙处于打开过程中 ，打开ing
                        break;
                    case BluetoothAdapter.STATE_ON://蓝牙已经打开
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF://蓝牙处于关闭过程中 ，关闭ing
                        break;
                    case BluetoothAdapter.STATE_OFF://蓝牙已经关闭
                        break;
                }
            }
            //与设备绑定状态
            else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
                switch (device.getBondState()){
                    case BluetoothDevice.BOND_NONE:
                        Toast.makeText(PairedActivity.this,"配对失败",Toast.LENGTH_SHORT).show();
                        break;
                    case BluetoothDevice.BOND_BONDING:
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        String deviceInfo = device.getName() + "\n" + device.getAddress();
                        pairedDiviceAdapter.add(deviceInfo);
                        for(int i=0;i<foundDeviceList.size();i++){
                            if(deviceInfo.equals(foundDeviceList.get(i))){
                                foundDiviceAdapter.remove(foundDeviceList.get(i));
                                break;
                            }
                        }
                        break;
                }
            }
            //发现设备
            else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //列表中存在则忽略
                String deviceInfo = device.getName() + "\n" + device.getAddress();
                for(int i=0;i<foundDeviceList.size();i++){
                    if(deviceInfo.equals(foundDeviceList.get(i))){
                        return;
                    }
                }
                //未配对设备才添加
                if(device.getBondState() != BluetoothDevice.BOND_BONDED){
                    addPrinterDevice(device);
                }
            }
            //断开连接
            else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                
            }
            //蓝牙搜素完成
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                popupWindow.dismiss();
                Toast.makeText(PairedActivity.this,"查找结束！",Toast.LENGTH_SHORT).show();
            }
        }
    };

    private void addPrinterDevice(BluetoothDevice device) {
        foundDiviceAdapter.add(device.getName() + "\n" + device.getAddress());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
